#endcoding:utf-8
class User < ActiveRecord::Base
  has_one :profile
  has_one :counselor_info
  has_one :factory_info
  validates :name, presence:true, length: { maximum: 50 }, uniqueness: true
  validates :email, presence:true, uniqueness: true, length: { maximum: 255 },format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i,message: "邮箱格式错误" }
  validates :password,confirmation:true,presence:true,length:{minimum: 6}
  validates :password_confirmation, presence: true
  has_secure_password
  attr_accessor :remember_token, :activation_token
  before_save :downcase_email
  before_create :create_activation_digest
  has_many :demands, dependent: :destroy
  has_many :offers, dependent: :destroy
  has_many :messages,dependent: :destroy
  has_many :question_read_logs
  has_many :active_evaluates, class_name: "Evaluate",
           foreign_key: "evaluater_id",
           dependent: :destroy
  has_many :passive_evaluates, class_name: "Evaluate",
           foreign_key: "evaluated_id",
           dependent: :destroy
  has_many :evaluating, through: :active_evaluates, source: :evaluated
  has_many :evaluaters, through: :passive_evaluates, source: :evaluater
#关注
  has_many :active_follows, class_name: "Follow",
           foreign_key: "follower_id",
           dependent: :destroy
  has_many :passive_follows, class_name: "Follow",
           foreign_key: "followed_id",
           dependent: :destroy
  has_many :following, through: :active_follows, source: :followed
  has_many :followers, through: :passive_follows, source: :follower

  def following?(other_member)
    following.include?(other_member)
  end
  def follow(other_member)
    active_follows.create(followed_id: other_member.id)
  end
  def unfollow(other_member)
    active_follows.find_by(followed_id: other_member.id).destroy
  end
  # 返回指定字符的哈希摘要
  def User.digest(string)
    cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
        BCrypt::Engine.cost
    BCrypt::Password.create(string, cost: cost)
  end
  #返回随机令牌
  def User.new_token
    SecureRandom.urlsafe_base64
  end
  def authenticated?(attribute, token)
    digest = send("#{attribute}_digest")
    return false if digest.nil?
    BCrypt::Password.new(digest).is_password?(token)
  end
  private
  def create_activation_digest
    self.activation_token = User.new_token
    self.activation_digest = User.digest(activation_token)
  end
  def downcase_email
    self.email = email.downcase
  end
end
